package gri_conversions;

use Data::Dumper;
use File::Basename;
use MIME::Base64;
use File::Temp qw(:mktemp);

#########################################################################
# Class level variables to record errors of last call.			#
#########################################################################

my $convert_errcode=0;
my $convert_errstr=undef;

sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self  = {};
my %args=@_;
my $tmpdir="/tmp";

	$convert_errcode=0;
	$convert_errstr=undef;
	my %C=();
	$C{"csv xls"}={
		desc	=> "Comma Separated File to Excel",
		code	=> \&gri_conversions::csv_to_xls,
	};
	
	if(exists($args{tmpdir})) {
		$tmpdir=$args{tmpdir};
	}
	$self->{conversions}={%C};
	$self->{tmpdir}=$tmpdir;
	bless($self,$class);
	return $self;
}

sub error {
	return($convert_errcode,$convert_errstr);
}

sub can_convert {
my $self=shift;
my $otype=shift;
my $ntype=shift;

	my $ckey=lc("$otype $ntype");
	if(exists($self->{conversions}->{$ckey})) {
		return 1;
	} else {
		return 0;
	}
}

sub do_convert {
my $self=shift;
my $otype=shift;
my $ntype=shift;
my $odata=shift;
my $cargs=shift;

	my $tmpdir=$self->{tmpdir};
	# For a conversion odata can be array ref, a filename, or a file descriptor...
	my $ckey=lc("$otype $ntype");
	if(! exists($self->{conversions}->{$ckey})) {
		return(-1,"No conversion facility available.");
	}
	
	my $data="";
	my $ref="";
	my $rmfile=0;
	my $tnam=mktemp("$tmpdir/conv_XXXXXXX");
	if(ref($odata)) {
		$ref=ref($odata);
		if($ref eq "GLOB") {
			$data=join("",<$odata>);
		} elsif($ref eq "ARRAY") {
			$data=join("",@$odata);
		} else {
			return(-1,"Unrecognised data input.");
		}
		my $fd;
		open($fd,">$tnam") or return(-1,"Unable to open file for writing.");
		print $fd $data;
		close($fd);
		$rmfile=1;
	} else {
		if(! -e $odata) {
			return(-1,"File '$odata' does not exist.");
		}
		if(! -f $odata || ! -r $odata) {
			return(-1,"File '$odata' is not a regular file or is not readable.");
		}
		$tnam=$odata;
	}
	rename($tnam,"$tnam.csv");

	$cargs="" if !defined($cargs);
	$cargs =~ s/^\s+//;
	$cargs =~ s/\s+$//;

	my $newname="";
	# If we do not have args then do a simple conversion
	if(!length($cargs)) {
		my $cmd="/opt/gri/bin/csv2xls.pl $tnam.csv";
		system("$cmd >/dev/null 2>/dev/null");
		my $x2="$tnam.xls";
		unlink("$tnam.csv") if $rmfile;
		if(! -f $x2) {
			return(-1,"Unable to perform conversion. [$cmd]");
		}
		$newname=$x2;
	} else {
		my $x2="$tnam.xls";
		my $cmd="/opt/gri/bin/se-csv2xls.pl --csv $tnam.csv --xls $x2 --overwrite $cargs";
		system("$cmd >/dev/null 2>&1");
		unlink("$tnam.csv") if $rmfile;
		if(! -f $x2) {
			return(-1,"Unable to perform conversion [$cmd].");
		}
		$newname=$x2;
	}
	if($rmfile==0) {
		return(1,$newname);
	} else {
		my $fd;
		if(!open($fd,$newname)) {
			# unlink($newname);
			return(-1,"Unable to open '$newname'.");
		}
		my $d=join("",<$fd>);
		close($fd);
		unlink($newname);
		return(1,$d);
	}
}

1;

# vim: ts=8:sw=8
